package com.zy.oauth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.common.core.constant.Constants;
import com.zy.oauth.cov.RolePermissionCov;
import com.zy.oauth.dto.AccountDto;
import com.zy.oauth.dto.RolePermissionDto;
import com.zy.oauth.dto.query.RolePermissionQuery;
import com.zy.oauth.entity.RolePermission;
import com.zy.oauth.mapper.RoleMapper;
import com.zy.oauth.mapper.RolePermissionMapper;
import com.zy.oauth.service.PermissionService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class PermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements PermissionService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public Set<String> getRolePermission(AccountDto account) {
        List<String> list = roleMapper.getRolePermission(account.getUserId());
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.stream().collect(Collectors.toSet());
    }

    @Override
    public List<RolePermissionDto> getMenuPermission(Set<String> roles) {
        List<RolePermission> list = new ArrayList<>();
        List<RolePermissionDto> dtoList = new ArrayList<>();
        //如果当前角色为admin
        if (roles.contains(Constants.ADMIN)) {
            list = baseMapper.all();
        } else {
            list = baseMapper.list(new RolePermissionQuery(), RolePermissionQuery.class);
        }

        list.forEach(e -> {
            RolePermissionDto dto = new RolePermissionDto();
            BeanUtils.copyProperties(e, dto);
            dtoList.add(dto);
        });

        List<RolePermissionDto> resultList = dtoList.stream().filter(v -> v.getParentId() == 0L).collect(Collectors.toList());
        resultList.forEach(e -> {
            List<RolePermissionDto> lll = dtoList.stream().filter(a -> a.getParentId() == e.getId()).collect(Collectors.toList());
            e.setChildren(lll);
        });

        return resultList;
    }

}
